package be.bonamis.timesheet.controller;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import be.bonamis.timesheet.dto.LoginDTO;
import be.bonamis.timesheet.model.Person;
import be.bonamis.timesheet.service.CreateDb;
import be.bonamis.timesheet.service.PersonService;

@Controller
@RequestMapping("/login")
public class LoginController extends AbstractController{
	
	private static final String LOGIN_VIEW = "login/login";
	private static final String FOLDER_CHOICE_VIEW = "folders/";
	
	@Resource
    private PersonService personService;
	
	@Autowired
	private CreateDb createDb;
	
	@RequestMapping(method = RequestMethod.POST)
	public String processForm(LoginDTO login/*, Model model*/) {
		Person person = personService.findByInitials(login.getInitials());
		if (person==null) {
			createDb.insertValues();
			person = personService.findByInitials(login.getInitials());
		}
		return createRedirectViewPath(FOLDER_CHOICE_VIEW + person.getId());
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView loginPage(Model model) {
		return goToLoginPage(model);
	}

	/**
     * This setter method should only be used by unit tests
     * @param personService
     */
    protected void setPersonService(PersonService personService) {
        this.personService = personService;
    }
    
    protected static ModelAndView goToLoginPage(Model model) {
		model.addAttribute("login", new LoginDTO());		
		return new ModelAndView(LOGIN_VIEW);
	}

}